<template>
  <div>
    <!-- 面包屑 -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回
      </el-button>
      <div class="ccui-navigation-divider" />
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{
            path: '/inventoryManagement'
          }"
          >库存管理(财务)
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{
            path: '/inventoryManagement/move-store'
          }"
          >财务移库管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{
            path: '/inventoryManagement/move-store'
          }"
          >财务移库
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">新增财务移库</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div v-if="isTrue" class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <baseInfo
              ref="baseInfo"
              :formData="formData"
              @getRowAim="getRowAim"
              @getRowOrg="getRowOrg"
            />
          </el-tab-pane>

          <el-tab-pane label="采购清单" name="second">
            <purchaseList
              ref="purchaseList"
              :purchaseData="purchaseData"
              :originalWarehouseId="formData.originalWarehouseId"
              :targetWarehouseId="formData.targetWarehouseId"
            />
          </el-tab-pane>

          <el-tab-pane label="附件" name="third" class="file-group">
            <div class="commonClass">
              <fileInfo
                ref="fileInfo"
                @fileIdArr="fileIdArr"
                :fileArrs="fileList"
              ></fileInfo>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandleKeep()"
            >暂存
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('submit')"
            >保存并提交
          </el-button>
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回
          </el-button>
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import baseInfo from "../components/baseInfo.vue";
import purchaseList from "../components/purchaseList.vue";
import fileInfo from "../components/files.vue";
import { saveSmpMoveInventory, tsMoveInventory } from "../api";
import { mapActions } from "vuex";
import { cloneDeep } from "lodash";
export default {
  components: { baseInfo, purchaseList, fileInfo },
  data() {
    return {
      activeName: "first",
      isTrue: false,
      fileList: [],
      purchaseData: [],
      uploadIds: [] //表格信息
    };
  },
  mounted() {
    console.log(
      this.$store.state.moveStore,
      this.$store.state.moveStore.moveInventoryCount,
      this.$store.state.moveStore.moveInventoryMoney,
      "---xx"
    );
  },
  methods: {
    addDate() {
      let nowDate = new Date();
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      };
      this.$refs.baseInfo.formData.reportTime =
        date.year + "/" + date.month + "/" + date.date + "";
    },
    submitHandle(name) {
      this.$refs.baseInfo.$refs.formData.validate(valid => {
        if (valid) {
          if (this.$refs.purchaseList.tableData.length <= 0) {
            this.$showErrorMessage("采购清单不能为空！");
            this.activeName = "second";
            return;
          } else {
            let transferLibraryCount = this.$refs.purchaseList.tableData.some(
              item => {
                return item.transferLibraryCount == 0;
              }
            );
            if (transferLibraryCount) {
              this.$showErrorMessage("移库数量不能为0！");
              this.activeName = "second";
              return;
            }
            if (name == "save") {
              this.saveHouse();
            } else {
              this.submitHouse();
            }
          }
        } else {
          this.$showErrorMessage("移库基本信息编辑不全，请编辑后保存！");
          this.activeName = "first";
        }
      });
    },
    // 暂存
    submitHandleKeep() {
      if (this.$refs.purchaseList.tableData) {
        this.$refs.purchaseList.tableData.forEach((item, index) => {
          item.sn = index;
          delete item._XID;
        });
      }

      const baseInfoData = cloneDeep(this.$refs.baseInfo.formData);
      baseInfoData.reportTime = Number(
        Date.parse(baseInfoData.reportTime) + ""
      );
      let obj = {
        moveInventoryBO: baseInfoData, //基本信息
        moveInventoryBillBOList: this.$refs.purchaseList.tableData, //清单列表
        moveInventoryBillBODelList: [], //删除清单列表
        uploadIds: this.uploadIds, //附件
        operType: "0"
      };
      tsMoveInventory(obj).then(res => {
        if (res.data.code == "0") {
          this.$message({
            type: "success",
            message: res.data.message,
            showClose: true,
            ccuiCustom: true,
            duration: 8000
          });
          this.addDate();
          // this.$router.push('/inventoryManagement/move-store/unSubmit');
          this.$router.go(-1);
          this.isTrue = false;
        }
      });
    },
    fileIdArr(value) {
      this.uploadIds = value;
    },
    // 保存
    saveHouse() {
      this.$refs.purchaseList.tableData.forEach((item, index) => {
        item.sn = index;
        delete item._XID;
      });
      //   console.log('保存我是转换前',this.$refs.baseInfo.formData.reportTime)
      //   this.$refs.baseInfo.formData.reportTime =
      //     Date.parse(this.$refs.baseInfo.formData.reportTime) + "";
      //     let reportTime = this.$refs.baseInfo.formData.reportTime;

      //   console.log('保存我是转换后',this.$refs.baseInfo.formData.reportTime);
      const baseInfoData = cloneDeep(this.$refs.baseInfo.formData);
      baseInfoData.reportTime = Number(
        Date.parse(baseInfoData.reportTime) + ""
      );
      baseInfoData.filesNumber = Number(baseInfoData.filesNumber);
      let obj = {
        moveInventoryBO: baseInfoData, //基本信息
        moveInventoryBillBOList: this.$refs.purchaseList.tableData,
        // moveInventoryBillBOList:purchaseArr,//采购清单
        uploadIds: this.uploadIds, //附件
        operType: "0" //保存
      };
      saveSmpMoveInventory(obj).then(res => {
        if (res.data.code == "0") {
          this.$message({
            type: "success",
            message: res.data.message,
            showClose: true,
            ccuiCustom: true,
            duration: 8000
          });
          //   this.addDate()
          // this.$router.push('/inventoryManagement/move-store/unSubmit');
          this.$router.go(-1);
          this.isTrue = false;
        }
      });
    },
    // 提交
    submitHouse() {
      this.$refs.purchaseList.tableData.forEach((item, index) => {
        item.sn = index;
        delete item._XID;
      });
      //   this.$refs.baseInfo.formData.reportTime =
      //     Date.parse(this.$refs.baseInfo.formData.reportTime) + "";
      const baseInfoData = cloneDeep(this.$refs.baseInfo.formData);
      baseInfoData.reportTime = Number(
        Date.parse(baseInfoData.reportTime) + ""
      );
      baseInfoData.filesNumber = Number(baseInfoData.filesNumber);
      let obj = {
        moveInventoryBO: baseInfoData, //基本信息
        moveInventoryBillBOList: this.$refs.purchaseList.tableData,
        // moveInventoryBillBOList:purchaseArr,//采购清单
        uploadIds: this.uploadIds, //附件
        operType: "1" //提交
      };
      saveSmpMoveInventory(obj).then(res => {
        console.log(res.data);
        if (res.data.code == "0") {
          this.$message({
            type: "success",
            message: res.data.message,
            showClose: true,
            ccuiCustom: true,
            duration: 8000
          });
          this.addDate();
          // this.$router.push('/inventoryManagement/move-store/list');
          this.$router.go(-1);
          this.isTrue = false;
        }
      });
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
      console.log(
        this.$store.state.moveStore.moveInventoryCount,
        this.$store.state.moveStore.moveInventoryMoney,
        "-----"
      );
    },
    handleBack() {
      this.$router.go(-1);
      this.isTrue = true;
    },
    // 原仓库
    getRowOrg(data) {
      console.log(data);
      this.formData.originalWarehouseName = data.warehouseName;
      this.formData.originalWarehouseId = data.id;
    },
    // 目标仓库
    getRowAim(data) {
      this.formData.targetWarehouseName = data.warehouseName;
      this.formData.targetWarehouseId = data.id;
    },
    ...mapActions(["setInventoryStatus"])
  },
  created() {
    this.$store.commit("setMoveInventoryCount", "");
    this.$store.commit("setMoveInventoryMoney", "");
    console.log(
      this.$store.state.moveStore,
      this.$store.state.moveStore.moveInventoryCount,
      this.$store.state.moveStore.moveInventoryMoney,
      "---xx"
    );
  },
  activated() {
    this.activeName = "first";

    this.fileList = [];
    this.uploadIds = [];
    this.formData = {
      reportInOrgName: "", //填报单位
      reportInOrgId: null, //填报单位id
      categoryName: "", //分类名称
      categoryCode: "", //分类名称编码
      moveInventoryName: "", //移库单名称
      moveInventoryCode: "", //移库单编号
      originalWarehouseName: "", //原仓库
      originalWarehouseId: null, //原仓库id
      originalWarehouseCode: "", //原仓库编码
      targetWarehouseName: "", //目标仓库
      targetWarehouseId: null, //目标仓库id
      targetWarehouseCode: "", //目标仓库编码
      moveInventoryCount: "", //移库数量
      moveInventoryMoney: "", //移库金额
      reportUsername: "", //编制人
      reportOpenid: "", //编制人id
      remark: "" //备注
    };
    this.formData.moveInventoryCount = "";
    // this.$set(this.formData, "reportTime", Date.parse(new Date()) + "");
    console.log(this.formData.reportTime);
    this.isTrue = true;
    this.$nextTick(() => {
      this.$refs.fileInfo.tableData = [];
      this.$refs.purchaseList.$refs.multipleTable.reloadData([]);
    });
  },
  deactivated() {
    this.setInventoryStatus(false);
  },
  watch: {
    // 如果路由有变化，会再次执行clear方法
    // "$route": "clear",
    $route(to, from) {
      this.$store.commit("setMoveInventoryCount", "");
      this.$store.commit("setMoveInventoryMoney", "");
      this.formData.moveInventoryCount = "";
      this.formData.moveInventoryMoney = "";
      this.purchaseData = [];
      console.log(
        to.path,
        from.path,
        this.$store.state.moveStore,
        this.$store.state.moveStore.moveInventoryCount,
        this.$store.state.moveStore.moveInventoryMoney
      );
    }
  }
};
</script>

<style lang="scss" scoped>
.commonClass {
  margin-top: 5px;
}
</style>
